	package com.irdstudio.efp.esb.api.rest.dxm;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.util.TraceUtil;
import com.irdstudio.efp.esb.api.bean.dxm.ReqLoanAdjLimitQryBean;
import com.irdstudio.efp.esb.api.bean.dxm.RespLoanAdjLimitQryBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.dxm.DxmEnum;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.limit.service.facade.LmtAdjustThirdService;
import com.irdstudio.efp.limit.service.vo.LmtAdjustThirdVO;

/**
  * 调额结果查询服务接口
  * @author  qiuyf
  * @since 2019年3月7日 下午4:06:32
  * @version 1.0
 */
@RestController
@RequestMapping("/esb")
public class LoanAdjustLimitQueryController {

	private static Logger logger = LoggerFactory.getLogger(LoanAdjustLimitQueryController.class);
	
	@Autowired
	@Qualifier("lmtAdjustThirdService")
	private LmtAdjustThirdService lmtAdjustThirdService;
	
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("获取ESB请求对象，校验 ESB请求系统头和请求应用头对象开始");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	@ModelAttribute("reqLoanAdjLimitQryBean")
	public ReqLoanAdjLimitQryBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("获取调额结果查询服务接口请求对象，校验调额结果查询服务接口请求体对象开始");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqLoanAdjLimitQryBean.class);
	}
	
	@PostMapping("/SERVICE_30230004_01")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
			@Validated @ModelAttribute("reqLoanAdjLimitQryBean") ReqLoanAdjLimitQryBean reqLoanAdjLimitQryBean, BindingResult br2, Exception exception) {
		String adjustId = reqLoanAdjLimitQryBean.getAdjAmtAppFlowNo(); //调额申请流水号，唯一标记一次调额
		String timeStamp = TimeUtil.getTimeStampByPattern("yyyyMMddHHmmssSSS"); //时间戳
		String globalSerno = esbReqServiceBean.getSysHead().getGlblSrlNo();
		TraceUtil.setTraceId(globalSerno);
		LmtAdjustThirdVO resVo = null;
		logger.info("调额结果查询服务接口处理开始---------- 调额申请流水号（唯一标记一次调额）:" + adjustId);
        try {
        	// 1. 通过切面校验额度调整结果查询请求参数是否正确，如不正确则返回错误信息
    		if (Objects.nonNull(exception)) {
    			throw exception;
    		}
    		// 2. 调用中台服务，查询“调整结果额度”
    		resVo = new LmtAdjustThirdVO();
    		resVo.setAdjAmtId(adjustId);
    		resVo = lmtAdjustThirdService.queryByAdjAmtId(resVo);
    		// 3. 组装返回报文
    		if(Objects.isNull(resVo)) {
    			throw new Exception("调额申请流水号：" + "【" + adjustId + "】" + "，不存在相应的调额申请记录，请核查！");
    		}else {
        		return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
    					buildRespLoanAdjLimitQryBean(timeStamp, EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "调额结果查询处理完成。", reqLoanAdjLimitQryBean, resVo).toString(),
    					EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "调额结果查询处理完成。");
    		}
        } catch (Exception e) {
        	logger.error("***********调用调额结果查询服务接口处理失败**************"+e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					buildRespLoanAdjLimitQryBean(timeStamp,EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage(), reqLoanAdjLimitQryBean, resVo).toString(),
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage());
		} finally {
			logger.info("调额结果查询服务接口处理结束---------- 调额申请流水号（唯一标记一次调额）:" + adjustId);
			TraceUtil.clear();
		}

	}
	
	private static RespLoanAdjLimitQryBean buildRespLoanAdjLimitQryBean(String timeStamp, String retCode, String rtnMsg, ReqLoanAdjLimitQryBean reqLoanAdjLimitQryBean, LmtAdjustThirdVO resVo) {
		String adjId = reqLoanAdjLimitQryBean.getAdjAmtAppFlowNo();
		logger.debug("*********组装调额结果查询服务接口响应bean开始...调额申请流水号（唯一标记一次调额）：" + adjId + "*********");
		RespLoanAdjLimitQryBean respLoanAdjLimitQryBean = new RespLoanAdjLimitQryBean();
		respLoanAdjLimitQryBean.setRetCd(retCode);
		respLoanAdjLimitQryBean.setRetMsg(rtnMsg);
		respLoanAdjLimitQryBean.setRepeatRqsBss(reqLoanAdjLimitQryBean.getRepeatRqsBss());
		respLoanAdjLimitQryBean.setBaiduSnId(reqLoanAdjLimitQryBean.getBaiduSnId());
		respLoanAdjLimitQryBean.setVerNo(reqLoanAdjLimitQryBean.getVerNo());
		respLoanAdjLimitQryBean.setAdvType(reqLoanAdjLimitQryBean.getAdvType());
		respLoanAdjLimitQryBean.setTxnTmstmp(timeStamp);
		//联机模式
		respLoanAdjLimitQryBean.setOlTp(DxmEnum.TxnModel.SYNC.getValue());
		
		if(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE().equals(retCode)) {
			respLoanAdjLimitQryBean.setRetStCd(resVo.getAdjStatus());
			// 返回状态码是000000成功，且额度调整状态为“拒绝”
			if(DxmEnum.LoanAdjustSts.REJECT.getVALUE().equals(resVo.getAdjStatus())) { 
				respLoanAdjLimitQryBean.setbDRsnCd(resVo.getRspCode()); 
				respLoanAdjLimitQryBean.setbDRsnCdDsc(resVo.getRspMsg());
			}
			else if(DxmEnum.LoanAdjustSts.PASS.getVALUE().equals(resVo.getAdjStatus())) {
				//调整后额度
				respLoanAdjLimitQryBean.setAdjAfterAmt(resVo.getAdjResultLmt().toString()); 
			}
		}
		logger.debug("*********组装调额结果查询服务接口响应bean结束！调额申请流水号（唯一标记一次调额）:" + adjId + ",返回码:" + retCode + ",返回信息:" + rtnMsg + "**********");
		return respLoanAdjLimitQryBean;
	}
	
	
}
